<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <!-- <el-form-item label="用户id" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户id"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item> -->
      <el-form-item label="部门" prop="deptId">
        <el-select
          v-loading="loading"
          v-model="queryParams.deptId"
          @change="() => handleQuery()"
          placeholder="请选择部门"
          filterable
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in deptList"
            :key="item.id"
            :value="item.id"
            :label="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用户名称" prop="userName">
        <el-select
          v-loading="loading"
          v-model="queryParams.userName"
          @change="() => handleQuery()"
          placeholder="请选择用户"
          filterable
          clearable
          style="width: 240px"
        >
          <el-option
            v-for="item in userListSource"
            :key="item.id"
            :value="item.id"
            :label="item.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="月份" prop="month">
        <el-date-picker
          v-model="queryParams.month"
          value-format="YYYY-MM-DD"
          type="month"
          placeholder="请选择月份"
          :clearable="false"
          :editable="false"
          :default-value="new Date()"
          class="!w-220px"
        />
      </el-form-item>
      <!-- <el-form-item label="放款金额" prop="money">
        <el-input
          v-model="queryParams.money"
          placeholder="请输入放款金额"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <!-- <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['system:rank:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button> -->
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['system:rank:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['system:rank:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
        <el-button @click="() => { showRankDialog() }" type="warning" plain>
          <Icon icon="ep:gold-medal" />
          排名
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <!-- <el-table-column type="selection" width="55" /> -->
      <!-- <el-table-column label="ID" align="center" prop="id" /> -->
      <!-- <el-table-column label="用户id" align="center" prop="userId" /> -->
      <el-table-column label="排名" align="center" width="60">
        <template #default="scope">
          {{ (queryParams.pageNo - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column label="用户名称" align="center" prop="userName" />
      <el-table-column label="放款金额(元)" align="center" prop="money" />
      <el-table-column label="月份" align="center" prop="month">
        <template #default="scope">
          {{ formatDate(scope.row.month) }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['system:rank:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['system:rank:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column> -->
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <RankForm ref="formRef" @success="getList" />

  <!-- 贷款客户数量排名 -->
  <RankDialog ref="rankDialogRef" :getData="getRankData" />
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import download from '@/utils/download'
import { RankApi, Rank } from '@/api/system/rank'
import * as DeptApi from '@/api/system/dept'
import RankForm from './RankForm.vue'
import RankDialog from './RankDialog.vue';
import { omit } from 'lodash-es'
import { customerApi } from '@/api/system/customer'

/** 排行榜 列表 */
defineOptions({ name: 'Rank' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<Rank[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数

function monthAtNow() {
  const now = new Date();
  return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-01`;
}

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  userId: undefined,
  userName: undefined,
  deptId: undefined,
  month: monthAtNow(),
  money: undefined
})
watch(
  () => queryParams.deptId,
  value => value && getListByDeptId(),
);
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await RankApi.getRankPage(queryParams.userName ? omit(queryParams, ['deptId']) : queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  const now = new Date()
  queryParams.month = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-01`

  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref();

const followUpList = ref([])
function getFollowUpList() {
  return customerApi.getFollowUpList().then((data) => {
    followUpList.value = data
  })
}

const deptList = ref([]);
function getDeptList() {
  return DeptApi.getSimpleDeptList().then(data => {
    deptList.value = data;
  });
}

const listByDept = ref([]);
function getListByDeptId() {
  return customerApi.getListByDeptId({ deptId: queryParams.deptId })
  .then((data) => {
    listByDept.value = data;
    !followUpList.value.length && (queryParams.userId = undefined);
  })
}

const userListSource = computed(() => {
  return queryParams.deptId ? listByDept.value : followUpList.value
});

const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await RankApi.deleteRank(id)
    message.success(t('common.delSuccess'))
    currentRow.value = {}
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除排行榜 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    await RankApi.deleteRankList(checkedIds.value)
    checkedIds.value = []
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: Rank[]) => {
  checkedIds.value = records.map((item) => item.id!)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await RankApi.exportRank(queryParams)
    download.excel(data, '排行榜.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
// 添加日期格式化函数
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}年${month}月${day}日`
}

const rankDialogRef = ref();
function showRankDialog() {
  const [YYYY, MM] = queryParams.month.split('-');
  const title = `${YYYY}年${MM}月放款金额排行`;
  rankDialogRef.value.open(title);
}

function getRankData() {
  return RankApi.getRankPage({
    pageNo: 1,
    pageSize: 10,
    month: queryParams.month,
  });
}

/** 初始化 **/
onMounted(() => {
  // 设置默认月份为当前月份
  const now = new Date()
  queryParams.month = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-01`
  getList()
  getDeptList();
  getFollowUpList()
})
</script>
